package com.example.blog.controller;

import com.example.blog.common.AjaxResult;
import com.example.blog.component.DrawCheckCode;
import com.example.blog.component.SecurityUtil;
import com.example.blog.component.SendEmail;
import com.example.blog.model.UserInfo;
import com.example.blog.service.UserService;
import org.apache.catalina.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @Question UserController
 * @Date 2023/1/6 10:14
 * @Solution
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    SendEmail sendEmail;
    //注册
    @RequestMapping("/reg")
    public Object reg(String username,String password) {
        //1.非空校验
        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1,"非法请求");
        }
        //2.添加
        int ret = userService.add(username, SecurityUtil.encrypt(password));
        if(ret==1) {
            return AjaxResult.success("注册成功",1);
        } else {
            return AjaxResult.fail(-1, "数据库添加出错");
        }
    }
    //登录
    @RequestMapping("/login")
    public int login(HttpServletRequest request,String username, String password,String code) {
        //1.非空校验
        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)) {
            return 0;//0为密码或用户名错误
        }
        //2.先校验验证码
        HttpSession session = request.getSession();
        String checkCode = (String) session.getAttribute("CHECKCODE");
        if(!code.equals(checkCode)) {
            return -1;//-1为验证码错误
        }
        //3.校验合法性
        UserInfo userInfo = userService.getByName(username);
        //校验密码
        if(userInfo==null || userInfo.getId()<=0) {
            return 0;
        } else {
            boolean result = SecurityUtil.decrypt(password,userInfo.getPassword());
            if(result==true) {
                //4.设置session
                session.setAttribute("user", userInfo.getId());
                //5.登录跳转由前端完成
                return 1;
            } else {
                return 0;
            }
        }
    }
    //获取文章作者
    @RequestMapping("/getaut")
    public UserInfo getAuthor(HttpServletRequest request,int userid) {
        return userService.getById(userid);
    }
    //获取用户卡信息
    @RequestMapping("/getinfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int id = (int)session.getAttribute("user");
        //根据id查询用户信息
        UserInfo userInfo = userService.getById(id);
        return userInfo;
    }

    //登出
    @RequestMapping("/logout")
    public boolean logOut(HttpServletRequest request) {
        //清除session
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        //检查seesion是否清楚成功
        if(session.getAttribute("user")==null) {
           return true;
        } else {
            return false;
        }
    }
    //验证码
    @RequestMapping("/code")
    public void makeCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
        //画验证码
        DrawCheckCode drawCheckCode = new DrawCheckCode();
        BufferedImage image = drawCheckCode.doDraw();
        //设置响应类型，告诉浏览器输出的内容是图片
        response.setContentType("image/jpeg");
        //设置响应头
        response.setHeader("Pragma","no-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setHeader("Expires","0");
        //将验证码的值保存在session中，方便查看
        request.getSession().setAttribute("CHECKCODE",drawCheckCode.getCheckCode());

        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpeg",outputStream);
        outputStream.flush();   //清空缓冲区数据
        outputStream.close();   //关闭流
    }
    //修改用户资料
    @RequestMapping("revise")
    public int revise(HttpServletRequest request,String col,String newValue,@Value("null") String username) {
        System.out.println(col);
        System.out.println(newValue);
        //拿到当前用户
        int id;
        if(username.equals("null")) {
            HttpSession session = request.getSession();
            id = (int) session.getAttribute("user");
        } else {
            id=userService.getByName(username).getId();
        }
        if(col.equals("email")) {
            return userService.reviseEm(newValue,id);
        } else if(col.equals("username")) {
            return userService.reviseUn(newValue,id);
        } else if(col.equals("password")) {
            return userService.revisePs(newValue,id);
        } else if(col.equals("profile")) {
            return userService.reviseProfile(newValue,id);
        } else {
            return 0;
        }
    }
    //检查邮箱是否正确
    @RequestMapping("/checke")
    public UserInfo checkEmail(String username) {
        UserInfo userInfo = userService.getByName(username);
        return userInfo;
    }
    //发送忘记密码邮件
    @RequestMapping("/sendmail")
    public void sendEmail(String username) {
        //根据username查询到该邮箱
        UserInfo userInfo = userService.getByName(username);
        String accept=userInfo.getEmail();
        sendEmail.sentOne(accept,username);
    }
}
